// pages/home/subscribe/list/com/houseListOld/houseListOld.js
const app = getApp();
import api from "../../../../../../common/api"
import locationBehavior from './../../../../../../behaviors/location';
import * as transferData from './../../../../../../models/transferData'
import * as filterConfig from './../../../../../../models/filter'
const cityMap = require('./../../../../../../utils/city')

const DEFAULT_TIME = '7'

Component({
  behaviors: [locationBehavior],
  /**
   * 组件的配置
   */
  options: {
    styleIsolation: 'isolated',
    pureDataPattern: /^_/
  },
  /**
   * 组件的属性列表
   */
  properties: {
    salesType: {
      type: String,
      value: 'sales'
    },
    districtOptions: {
      type: Array,
      value: []
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    _listStartTime: null,
    isOpenCity: true,
    cityName: '',
    cityCode: '',
    search: {},
    pageIndex: 0,
    pageSize: 20,
    houseList: [],
    hasMoreList: true,
    filterDistrict: {},
    filterDistrictOptions: [],
    filterMore: {
      time: DEFAULT_TIME
    },
    filterMoreOptions: [],
  },

  /**
   * 组件的数据监听
   */
  observers: {
    districtOptions(val) {
      app.globalData.loginPromise.then(() => {
        if (val && val.length) {
          this.initFilterConfig()
        }
      })
    }
  },

  /**
   * 组件的生命周期
   */
  lifetimes: {
    attached: function () {
      app.globalData.loginPromise.then(() => {
        this.initFilterConfig()
        this.getCurrentCity()
          .then(() => {
            this.loadHouse()
          })
      })
    },
    detached: function () {},
  },

  /**
   * 页面的生命周期
   */
  pageLifetimes: {
    show: function () {
      this.refreshCity()
      this.refreshMove()
    },
    hide: function () {
      // 页面被隐藏
    },
    resize: function (size) {
      // 页面尺寸变化
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {

    initFilterConfig() {
      const {
        salesType,
        districtOptions
      } = this.data
      this.setData({
        filterDistrictOptions: [{
          // restrict: true,
          // tier: 1,
          // colors: ['#f8f8f8', '#fff'],
          id: 'district',
          cascader: districtOptions
        }],
        filterMoreOptions: [{
          id: 'time',
          title: '时间',
          single: filterConfig.rangeAddTime,
          defaultValue: DEFAULT_TIME
        }, {
          id: 'price',
          title: `价格区间(${salesType === 'sales' ? '万' : '元'})`,
          input: {},
          multi: salesType === 'sales' ? filterConfig.rangeSalesPrice : filterConfig.rangeRentPrice
        }, {
          id: 'area',
          title: '建筑面积',
          input: {},
          multi: filterConfig.rangeArea
        }, {
          id: 'type',
          title: '户型',
          multi: filterConfig.rangeHouseType
        }],
      })
    },

    onPageReachBottom() {
      this.loadHouse()
    },

    getCurrentCity() {
      return new Promise((resolve, reject) => {
        this.getCityBe(true)
          .then((city) => {
            let cityCode = ''
            cityMap.cityObjs.forEach(item => {
              if (item.city === city) {
                cityCode = item.code || ''
              }
            })
            if (cityCode) {
              this.setData({
                cityName: city,
                cityCode: cityCode,
              });
            } else {
              this.setData({
                cityName: '上海市',
                cityCode: '310000',
              });
            }
            resolve()
          })
          .catch(() => {
            this.setData({
              cityName: '上海市',
              cityCode: '310000',
            });
            resolve()
          })
      })
    },

    onSearchChange(e) {
      this.setData({
        search: e.detail,
      })
      this.resetHouseData()
      this.clearFilter()
      this.loadHouse()
    },

    clearFilter() {
      this.setData({
        filterMore: {
          time: DEFAULT_TIME
        },
        filterDistrict: {},
      });
      const child = this.selectComponent("#dropdowns");
      child && child.onClear();
    },

    onFilterChange(e) {
      let name = e.currentTarget.dataset.name
      let path = `filter${name}`
      this.setData({
        [path]: e.detail.form,
      })

      this.resetHouseData()
      this.loadHouse()
    },

    resetHouseData() {
      this.setData({
        houseList: [],
        pageIndex: 0,
        hasMoreList: true,
      })
      wx.pageScrollTo({
        scrollTop: 0,
        duration: 0
      })
    },

    resetHouseFilter() {
      this.setData({
        filterDistrict: {},
        filterMore: {
          time: DEFAULT_TIME
        },
      })
    },

    loadHouse() {
      let t = this
      return new Promise((resolve, reject) => {
        let {
          pageIndex,
          pageSize,
          cityCode,
          hasMoreList,
          search,
          salesType,
          filterDistrict,
          filterMore
        } = t.data
        if (!hasMoreList) {
          resolve()
          return
        }
        wx.showLoading({
          title: '加载中...',
        })
        let currentIndex = pageIndex + 1
        if (currentIndex === 1) {
          this.data._listStartTime = new Date().getTime()
        }
        let newFilterMore = filterConfig.parseFilter(filterMore)
        api.newAddHouseList({
          bizcircleIdList: filterConfig.parseDistrictFilter(filterDistrict.district),
          areaCode: filterConfig.parseAreaFilter(filterDistrict.district),
          areaList: newFilterMore.area,
          newExternalTime: newFilterMore.time,
          shiNumList: newFilterMore.type,
          priceList: newFilterMore.price,
          saleType: salesType.toUpperCase(),
          cityCode: cityCode,
          hdResblockId: search.type === 'id' ? search.value : '',
          keyword: search.type === 'key' ? search.value : '',
          lastTime: this.data._listStartTime || null,
          pageSize: pageSize,
          pageNum: currentIndex,
        }, (res) => {
          wx.hideLoading()
          if (res && res.data && res.data.isSuccess) {
            if (res.data.successMessage === '201') {
              t.setData({
                isOpenCity: false
              })
              resolve()
            }
            if (res.data.successMessage === '200') {
              let result = res.data.content || {}
              let list = result.list || []
              let maxIndex = result.pages
              let formatList = list.map(item => {
                let price = item.price || 0
                return {
                  houseLinkUrl: item.mobileUrl || '',
                  houseCommunityID: item.communityId || '',
                  houseCommunityName: item.communityName || '',
                  houseTitle: item.title || '',
                  houseDescribe: item.contentDescribe || '',
                  houseType: item.saleType || '',
                  houseImg: item.fileUrl || '',
                  houseRoom: item.shi || 0,
                  houseHall: item.ting || 0,
                  houseArea: item.buildingSize || '',
                  houseAddTime: item.releaseDateStr || '',
                  housePrice: item.saleType === "SALES" ? price / 10000 : price,
                  houseSource: item.externalName || '',
                  houseAreaPrice: item.unitPriceStr ? item.unitPriceStr.replace(',', '') : '',
                  houseIsMove: item.isMoveHouse || false,
                  houseFocusNum: item.focusNum || 0,
                }
              })
              if (currentIndex === 1) {
                t.data.houseList = [...formatList]
              } else {
                t.data.houseList.push(...formatList)
              }
              t.setData({
                pageIndex: currentIndex,
                hasMoreList: currentIndex >= maxIndex ? false : true,
                houseList: t.data.houseList
              })
              resolve()
            }
          } else {
            reject()
          }
        }, () => {
          wx.hideLoading()
          reject()
        });
      })
    },

    // 检察城市更新
    refreshCity() {
      if (transferData.getData('currentCity')) {
        transferData.resetData('currentCity')
        wx.redirectTo({
          url: `/pages/home/subscribe/list/list?tab=${this.data.salesType}`,
        })
      }
    },

    // 检察搬家更新
    refreshMove() {
      if (transferData.getData('isRefreshSubscribe')) {
        transferData.resetData('isRefreshSubscribe')
        this.resetHouseData()
        this.loadHouse()
      }
    },


  }
})